﻿using UnityEngine;

namespace SG
{

    public class InstanceHelper : MonoBehaviour
    {

        static GameObject globalSingleton;
        public static readonly string TagSingleton = "__SingletonGlobal__";
        static bool isInit = false;
        public static GameObject GetSingletonRoot()
        {
            if (globalSingleton == null)
            {
                globalSingleton = GameObject.Find(TagSingleton);
                if (globalSingleton == null)
                {
                    globalSingleton = new GameObject(TagSingleton);
                }
            }
            if (Application.isPlaying)
            {
                if (!isInit)
                {
                    DontDestroyOnLoad(globalSingleton);
                    isInit = true;
                }
            }
            return globalSingleton;
        }
        public static T Singleton<T>() where T : Component
        {
            XKLog.Log(typeof(T));
            return GetSingletonRoot().GetOrAddComponent<T>();
        }
    }
}